<?php
// @formatter:off
/**
 * @file tester.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: tester.php 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/services/tester.php $
 */
// @formatter:on

require_once __DIR__."/../config/defines.php";

define("__INDEX__", true);

require_once __DIR__."/../config/config.php";

if(defined("WC_NOT_INSTALLED")) {
	header("Location: ../");
} else {
	require_once "{$wcPaths["includes-directory"]}/dynamic.conf.php";
	require_once "{$wcPaths["includes-directory"]}/tools.php";

	$config = json_decode(file_get_contents("./tester.json"));
	$services = $config->services;
	sort($services);
	?>
	<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml">
		<head>
			<title><?php echo $wcSite["name"]; ?>:
				Service Tester</title>
			<link rel="icon" type="image/png" href="../images/wcomix.png"/>
			<link rel="stylesheet" type="text/css" href="../includes/jqueryui/<?php echo $wcVersions["jqueryui"]; ?>/jquery-ui-<?php echo $wcVersions["jqueryui"]; ?>.custom.css"/>
			<script type="text/javascript" src="../includes/jquery/<?php echo $wcVersions["jquery"]; ?>/jquery-<?php echo $wcVersions["jquery"]; ?>.min.js"></script>
			<script type="text/javascript" src="../includes/jqueryui/<?php echo $wcVersions["jqueryui"]; ?>/jquery-ui-<?php echo $wcVersions["jqueryui"]; ?>.custom.min.js"></script>
			<script type="text/javascript" src="../includes/jqueryui/<?php echo $wcVersions["jqueryui"]; ?>/jquery.ui.core.min.js"></script>
			<script type="text/javascript" src="../includes/jqueryui/<?php echo $wcVersions["jqueryui"]; ?>/jquery.ui.position.min.js"></script>
			<script type="text/javascript" src="../includes/jqueryui/<?php echo $wcVersions["jqueryui"]; ?>/jquery.ui.autocomplete.min.js"></script>
			<script type="text/javascript" src="../includes/jquery.cookie.js"></script>
			<script type="text/javascript" src="../includes/WCShortCuts.js"></script>
			<script type="text/javascript" src="../includes/rateit/jquery.rateit.min.js"></script>
			<script type="text/javascript" src="../includes/WCSimpleContainer.js"></script>
			<style type="text/css">
				#Caller {
					font-size: small;
					margin-left: auto;
					margin-right: auto;
					width: 600px;
				}
				#Caller select {
					width: 100%;
				}
				#Caller table {
					border-collapse: collapse;
					border-spacing: 0px;
					width: 100%;
				}
				#Caller table tr td {
					border-bottom: 1px LightGray solid;
					vertical-align: top;
				}
				div.Request span.title, div.Results span.title {
					font-size: small;
					font-weight: bold;
					text-decoration: underline;
				}
				div.Request pre {
					background-color: #e0e0d0;
					border: solid #a60000 1px;
					font-size: x-small;
					padding: 5px;
				}
				div.Results pre {
					background-color: #e0e0e0;
					border: solid #a60000 1px;
					font-size: x-small;
					padding: 5px;
				}
				div.Request pre.Good {
					background-color: #e0ffe0;
				}
				div.Request pre.Bad {
					background-color: #ffe0e0;
				}
			</style>
			<script type="text/javascript">
				var PARAMS_ID = 0;
				var LAST_RESULTS = null;
				var LAST_INTERFACE = null;
				var LAST_SEARCH = null;

				function AddParam() {
					PARAMS_ID++;

					var html = '<tr id="ParamRow_' + PARAMS_ID + '">';
					html += '<td><input type="text" id="ParamName_' + PARAMS_ID + '"/></td>';
					html += '<td><input type="text" id="ParamValue_' + PARAMS_ID + '"/></td>';
					html += '<td><input type="button" value="Remove" onClick="$(\'#ParamRow_' + PARAMS_ID + '\').remove();return false;"/></td>';
					html += '</tr>';

					$("#Params").append(html);

					ReShape();
				}

				function AddURLParam() {
					PARAMS_ID++;

					var html = '<tr id="URLParamRow_' + PARAMS_ID + '">';
					html += '<td><select id="URLParamName_' + PARAMS_ID + '">';
					html += '<option value="">[select a name]</option>';
					html += '<option value="collection">collection</option>';
					html += '<option value="comic">comic</option>';
					html += '<option value="directory">directory</option>';
					html += '<option value="image">image</option>';
					html += '<option value="rule">rule</option>';
					html += '<option value="tag">tag</option>';
					html += '<option value="MANUAL">[MANUAL]</option>';
					html += '</select></td>';
					html += '<td><input type="text" id="URLParamValue_' + PARAMS_ID + '"/></td>';
					html += '<td><input type="button" value="Remove" onClick="$(\'#URLParamRow_' + PARAMS_ID + '\').remove();return false;"/></td>';
					html += '</tr>';

					$("#URLParams").append(html);

					ReShape();
				}

				function CallService() {
					$("#Request").text("");
					$("#Interface").text("");
					$("#Search").text("");
					$("div.Request pre").removeAttr("class");

					var info = "";

					var params = {};
					var urlParams = "";
					var method = $("#Method").val();
					var group = $("#Group").val();
					var service = $("#Service").val();

					info += "Service: '" + service + "'\n";
					info += "Method: '" + method + "'\n";

					if (group != "") {
						urlParams += "&group=" + group;
						info += "Group: '" + group + "'\n";
					}

					info += "Params:\n";
					$("[id^='ParamRow_']").each(function() {
						var name = $(this).find("[id^='ParamName_']").val();

						if (name) {
							value = $(this).find("[id^='ParamValue_']").val();
							params[name] = ExplodeParamValue(value);
							info += "\t'" + name + "': '" + params[name] + "'\n";
						}
					});

					info += "URL Params:\n";
					$("[id^='URLParamRow_']").each(function() {
						var name = $(this).find("[id^='URLParamName_']").val();
						var value = $(this).find("[id^='URLParamValue_']").val();

						if (name == "MANUAL") {
							urlParams += "&" + value;
							info += "\tMANUAL: '" + value + "'\n";
						} else if (name != "") {
							urlParams += "&" + name + "=" + value;
							info += "\t'" + name + "': '" + value + "'\n";
						}
					});

					urlParams = "?service=" + service + urlParams;
					info += "Builts:\n";
					info += "\tURL Params: " + urlParams + "\n";
					info += "\tParams: " + JSON.stringify(params) + "\n";

					if (!service) {
						$("#Service").focus();
						alert("Service not specified");
					} else {
						$("#Results").text("Loading...");
						$("#ResultsData").text("Loading...");

						jQuery.getJSON("../service.php" + urlParams + "&explaininterface", function(data) {
							InterfacePrompt(data);
						});
						jQuery.getJSON("../service.php" + urlParams + "&explainsearch", function(data) {
							SearchPrompt(data);
						});

						if ($("#InterfaceOnly:checked").length > 0) {
							$("#Results").text("");
							$("#ResultsData").text("");
						} else {
							$.ajax({
								url: "../service.php" + urlParams,
								type: method,
								dataType: "json",
								data: {
									params: JSON.stringify(params)
								},
								success: function(data, textStatus, jqXHR) {
									ServicePrompt(data);
								},
								error: function(jqXHR, textStatus, errorThrown) {
									$("#Results").text(jqXHR.responseText);
									$("#ResultsData").text("");

									$("#Results").attr({
										class: ""
									});

									$("div.Request pre").attr({
										class: "Bad"
									});
								}
							});
						}
					}

					$("#Request").text(info);
				}

				function ExplodeParamValue(value) {
					var out = value;

					if (value.match(/^\[\]/)) {
						var separator = value.substring(2, 3);
						var value = value.substring(3);
						out = value.split(separator);
					}

					return out;
				}

				function InterfacePrompt(data) {
					LAST_INTERFACE = data;

					if (data) {
						var text = "";

						text += "Methods:\n";
						data.methods.forEach(function(item) {
							text += "\t- " + item + "\n";
						});

						text += "\n";
						text += "Permissions:\n";
						var noPermissions = true;
						if (data.permissions.all.length > 0) {
							noPermissions = false;
							text += "\tAll required:\n";
							data.permissions.all.forEach(function(item) {
								text += "\t\t- [" + item.code + "] " + item.name + "\n";
							});
						}
						if (data.permissions.any.length > 0) {
							noPermissions = false;
							text += "\tAt least one of:\n";
							data.permissions.any.forEach(function(item) {
								text += "\t\t- [" + item.code + "] " + item.name + "\n";
							});
						}
						if (noPermissions) {
							text += "\tNone\n";
						}

						text += "\n";
						text += "Parameters:\n";
						var noParameters = true;
						if (data.params.url.length > 0) {
							noParameters = false;
							text += "\tIn the URL:\n";
							data.params.url.forEach(function(item) {
								text += "\t\t- " + item + "\n";
							});
						}
						if (data.params.params.length > 0) {
							noParameters = false;
							text += "\tSerialized in 'params':\n";
							data.params.params.forEach(function(item) {
								text += "\t\t- " + item + "\n";
							});
						}
						if (noParameters) {
							text += "\tNone\n";
						}

						text += "\n";
						text += "Affected by ReadOnlyMode: " + (data.readonlyconflict ? "Yes" : "No") + "\n";

						$("#Interface").text(text);
					}
				}

				function ReShape() {
					$("input[type!=checkbox]").css("width", "100%");
				}

				function SearchPrompt(data) {
					LAST_SEARCH = data;

					if (data) {
						var text = "";

						text += "Class: '" + data.class.name + "' (" + (data.class.found ? "Found" : "Not found") + ")\n\n";
						text += "Paths:\n";
						data.paths.forEach(function(item) {
							text += "\t- '" + item.filename + "': " + (item.found ? "Found" : "Not found") + "\n";
						});

						$("#Search").text(text);
					}
				}

				function ServicePrompt(data) {
					LAST_RESULTS = data;

					$("#Results").attr({
						class: ""
					});

					var txt = "";
					if (!data.status) {
						$("div.Request pre").attr({
							class: "Bad"
						});
					} else {
						$("div.Request pre").attr({
							class: "Good"
						});
					}

					txt += "Row Count:   " + data.count + "\n";
					txt += "Code:        " + data.error.code + "\n";
					if (typeof data.transaction !== "undefined") {
						txt += "Transaction: " + data.transaction + "\n";
					}
					txt += "Message:     " + data.error.message + "\n";
					if (data.error.info.file) {
						txt += "\tAt: " + data.error.info.file + ":" + data.error.info.line + "\n";
						if (data.error.list) {
							txt += "\tErrors List:\n";
							data.error.list.forEach(function(item) {
								txt += "\t\t[" + item.code + "] " + item.message + " [" + item.info.caller + "] (" + item.info.file + ":" + item.info.line + ")\n";
							});
						}
					}

					$("#Results").text(txt);
					$("#ResultsData").text(sprint_r(data.data));
				}

				function sprint_r(theObj, spacer) {
					var out = "";

					if (!spacer) {
						spacer = "";
					}

					out += spacer + typeof (theObj) + "(\n";
					if (theObj.constructor == Array || theObj.constructor == Object) {
						for (var p in theObj) {
							if (theObj[p].constructor == Array || theObj[p].constructor == Object) {
								out += spacer + "\t'" + p + "' => " + typeof (theObj) + "(\n";
								out += sprint_r(theObj[p], spacer + "\t\t");
								out += spacer + "\t)\n";
							} else {
								out += spacer + "\t'" + p + "' => '" + theObj[p] + "'\n";
							}
						}
					}
					out += spacer + ")\n";

					return out;
				}

				$(function() {
					ReShape();
				});
			</script>
		</head>
		<body>
			<form id="Caller" action="#" method="get" onsubmit="CallService();
					return false;">
				<table>
					<tr>
						<td>Method:</td><td>
							<select id="Method">
								<option value="GET" >GET</option>
								<option value="POST">POST</option>
							</select></td>
					</tr>
					<tr>
						<td>Service:</td><td>
							<select id="Service">
								<option value="">[select a service]</option>
								<?php
								foreach($services as $srv) {
									echo "\t\t\t\t\t<option value=\"{$srv}\">{$srv}</option>";
								}
								?>
							</select></td>
					</tr>
					<tr>
						<td>Group:</td><td>
							<select id="Group">
								<option value="">[select a group]</option>
								<?php
								$items=WCGroupsHolder::I()->items() ;
								uasort($items,"WCGroup::NameSort");
								foreach($items as $group) {
									echo "\t\t\t\t\t<option value=\"{$group->id}\">{$group->name}</option>";
								}
								?>
							</select></td>
					</tr>
					<tr>
						<td>URL Params:</td>
						<td>
							<table id="URLParams">
								<tr>
									<td colspan="3">
										<input type="button" value="Add Param" onclick="AddURLParam();
												return false;"/>
									</td>
								</tr>
							</table></td>
					</tr>
					<tr>
						<td>Params:</td>
						<td>
							<table id="Params">
								<tr>
									<td colspan="3">
										<input type="button" value="Add Param" onclick="AddParam();
												return false;"/>
									</td>
								</tr>
							</table></td>
					</tr>
					<tr>
						<td colspan="2">
							<input id="InterfaceOnly" type="checkbox"/><label for="InterfaceOnly">Interface Only</label>
						</td>
					</tr>
					<tr>
						<td colspan="2">
							<input type="submit" value="Test Service"/>
						</td>
					</tr>
				</table>
			</form>

			<div class="Request">
				<span class="title">Sent information:</span>
				<pre id="Request">&nbsp;</pre>
			</div>
			<div class="Results">
				<span class="title">Result status and information:</span>
				<pre id="Results">&nbsp;</pre>
			</div>
			<div class="Results">
				<span class="title">Interface:</span>
				<pre id="Interface">&nbsp;</pre>
			</div>
			<div class="Results">
				<span class="title">Search:</span>
				<pre id="Search">&nbsp;</pre>
			</div>
			<div class="Results">
				<span class="title">Data:</span>
				<pre id="ResultsData">&nbsp;</pre>
			</div>
		</body>
	</html>
	<?php
}
?>
